<route lang="json5">
{
  style: {
    navigationBarTitleText: '佰汇签一签',
    enableShareAppMessage: true,
  },
}
</route>

<template>
  <view class="h-screen overflow-hidden bg-gray-100" :style="{ fontSize: settingsStore.fontSize }">
    <view
      class="flex flex-col items-center justify-start"
      :style="{
        paddingTop: safeAreaInsets?.top + 'px',
        color: settingsStore.themeColor,
        fontSize: settingsStore.fontSize,
      }"
    >
      <view class="bg-white w-88 h-120 rounded-3xl py-2 shadow-md mt-4">
        <!-- 公司信息卡片 -->
        <view class="w-11/12 p-4 rounded-lg">
          <view class="text-center">
            <view class="flex justify-center items-end space-x-2">
              <text class="text-3xl font-extrabold tracking-wide leading-tight">Braintec</text>
              <text class="text-3xl text-gray-600 font-semibold tracking-widest">佰汇技术</text>
            </view>
            <view class="mt-2 text-gray-600 tracking-wide">PLM+ERP+WMS+MES一体化解决方案</view>
            <view class="mt-1 text-gray-600 tracking-wide">数字化工厂建设标准产品服务引领者</view>
          </view>
        </view>

        <!-- 当前日期卡片 -->
        <view class="w-11/12 mt-2 p-4 rounded-lg">
          <view class="flex justify-between items-center">
            <text class="text-gray-600">当前日期</text>
            <text class="font-medium">{{ currentDate }}</text>
          </view>
        </view>

        <!-- 签到按钮外圈背景 -->
        <view class="mt-8 flex items-center justify-center">
          <view
            class="outer-circle"
            :style="{
              backgroundColor: todayIscheckIn ? '#d2f092' : settingsStore.themeLightColor + 80,
            }"
          >
            <!-- 签到按钮内圈 -->
            <view class="inner-circle shadow-lg p-2 bg-white" @tap="handleCheckIn">
              <image
                v-if="todayIscheckIn"
                src="/static/over.svg"
                class="w-16 h-16"
                mode="aspectFit"
              />
              <image v-else src="/static/checkin.svg" class="w-16 h-16" mode="aspectFit" />
              <text
                class="mt-2 text-sm"
                :style="{ color: todayIscheckIn ? '#d2f092' : settingsStore.themeColor }"
              >
                {{ todayIscheckIn ? '已签到' : '签到' }}
              </text>
            </view>
          </view>
        </view>

        <!-- 登录/公司信息提示 -->
        <view
          v-if="!isLoggedIn || !userStore.userInfo?.companyName"
          class="w-11/12 mt-6 p-4 rounded-lg text-center"
        >
          <view
            v-if="!isLoggedIn"
            class="text-sm underline"
            :style="{ color: settingsStore.themeColor }"
            @tap="navigateToLogin"
          >
            未登录 ，点击前往
            <span class="font-bold">登录</span>
          </view>
          <view
            v-else-if="!userStore.userInfo?.companyName"
            :style="{ color: settingsStore.themeColor }"
            class="text-sm underline"
            @tap="navigateToCompanyInfo"
          >
            公司信息未完善 ，点击前往
            <span class="font-bold">完善</span>
          </view>
        </view>

        <!-- 签到信息展示卡片 -->
        <view
          v-if="todayIscheckIn"
          class="w-11/12 mt-6 p-4 rounded-lg text-center text-sm"
          :style="{ color: '#999', fontSize: settingsStore.fontSize }"
        >
          <view>签到时间：{{ checkInTime }}</view>
          <view>签到人：{{ userStore.userInfo?.name || '未登录' }}</view>
        </view>
      </view>
    </view>
  </view>
</template>

<script lang="ts" setup>
import { ref } from 'vue'
import { useUserStore } from '@/store/user'
import { useCheckInStore } from '@/store/checkData'
import { useSettingsStore } from '@/store/settings'
import { useToast } from 'wot-design-uni'
import { checkIn } from '@/api/company'
import dayjs from 'dayjs'

const toast = useToast()
const userStore = useUserStore()
const checkInStore = useCheckInStore()
const settingsStore = useSettingsStore()

const currentTime = ref('')
const currentDate = ref('')
const todayIscheckIn = ref(false)
const checkInTime = ref('')
const isLoggedIn = ref(false)
let timer = ref(null)

// 安全区域信息
let safeAreaInsets
const systemInfoW = uni.getSystemInfoSync()
safeAreaInsets = systemInfoW.safeAreaInsets

const updateTime = () => {
  const now = new Date()
  currentTime.value = `${now.getHours()}:${now.getMinutes().toString().padStart(2, '0')}`
  currentDate.value = `${now.getFullYear()}年${now.getMonth() + 1}月${now.getDate()}日`
}

const navigateToLogin = () => {
  uni.navigateTo({ url: '/pages/login/index' })
}

const navigateToCompanyInfo = () => {
  uni.navigateTo({ url: '/pages/mine/info/index' })
}

const showLoginModal = async (): Promise<boolean> => {
  return new Promise((resolve) => {
    uni.showModal({
      title: '提示',
      content: '您需要先【登录】才能继续操作',
      confirmText: '立即登录',
      success: (res) => {
        if (res.confirm) navigateToLogin()
        resolve(res.confirm)
      },
    })
  })
}

const showCompanyInfoModal = async (): Promise<boolean> => {
  return new Promise((resolve) => {
    uni.showModal({
      title: '提示',
      content: '请先【完善公司信息】后再进行签到操作',
      confirmText: '去完善',
      success: (res) => {
        if (res.confirm) navigateToCompanyInfo()
        resolve(res.confirm)
      },
    })
  })
}

const handleCheckIn = async () => {
  try {
    if (!isLoggedIn.value) {
      await showLoginModal()
      return
    }

    if (!userStore.userInfo?.companyName) {
      await showCompanyInfoModal()
      return
    }

    if (todayIscheckIn.value) {
      toast.info('今天已经签到了')
      return
    }

    const data = {
      date: dayjs().format('YYYY-MM-DD'),
      userId: userStore.userInfo.userId,
    }

    uni.showLoading({
      title: '签到中...',
      forbidClick: true,
      loadingType: 'spinner',
    })

    const res = await checkIn(data)
    if (res.msg !== 'success') return

    const time = res.data.checkTime
    await handleCheckInByQrcode(time)

    setTimeout(() => toast.success('签到成功'), 300)
  } catch (error: any) {
    const time = error.data?.data?.checkTime
    if (error.data?.msg === '今天已签到') {
      await handleCheckInByQrcode(time)
    } else {
      toast.error('签到失败')
      console.error('签到异常:', error)
    }
  } finally {
    setTimeout(() => uni.hideLoading(), 300)
  }
}

const handleCheckInByQrcode = async (time: string) => {
  const obj = {
    userId: userStore.userInfo.userId,
    checkInTime: time,
    companyName: userStore.userInfo.companyName,
    name: userStore.userInfo.name,
  }
  checkInStore.addCheckIn(obj)
  todayIscheckIn.value = true
  checkInTime.value = time
}

const initData = async () => {
  isLoggedIn.value = !!uni.getStorageSync('access_token')
  if (isLoggedIn.value) {
    const records = await checkInStore.getTodayRecords()
    todayIscheckIn.value = records.length > 0
    if (todayIscheckIn.value) {
      checkInTime.value = records[0]?.checkInTime || ''
    }
  }
}

const initTime = () => {
  updateTime()
  timer.value = setInterval(updateTime, 60000)
}

const clearTimer = () => {
  if (timer.value) {
    clearInterval(timer.value)
    timer.value = null
  }
}

onShow(async () => {
  initTime()
  await initData()
})

onLoad(async (e) => {
  initTime()
  await initData()
  if (e?.scene) {
    try {
      if (!isLoggedIn.value) {
        await showLoginModal()
        return
      }
      if (!userStore.userInfo?.companyName) {
        await showCompanyInfoModal()
        return
      }
      await handleCheckIn()
    } catch (error) {
      toast.error('处理场景值失败')
      console.error('处理场景值失败:', error)
    }
  }
})
onLaunch(() => {
  console.log('App Launch')
  // @ts-ignore: 2322
  uni.onShareAppMessage(() => {
    return {
      title: '佰汇签一签', // 默认标题
      path: '/pages/index/index', // 默认跳转路径
      imageUrl: '/static/logo.png', // 默认分享图片
    }
  })

  // 如果需要分享到朋友圈（微信小程序独有）
  // @ts-ignore: 2322
  uni.onShareTimeline(() => {
    return {
      title: '佰汇签一签',
      query: '', // 自定义参数
      imageUrl: '/static/logo.png',
    }
  })
})

onUnload(() => {
  clearTimer()
})
</script>

<style scoped>
.outer-circle {
  width: 240rpx;
  height: 240rpx;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.inner-circle {
  width: 180rpx;
  height: 180rpx;
  border-radius: 50%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: #fff;
}

.shadow-lg {
  box-shadow:
    0 10px 15px -3px rgba(0, 0, 0, 0.1),
    0 4px 6px -2px rgba(0, 0, 0, 0.05);
}
</style>
